using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Sunny.UI;
using Serilog;
using WinApp.Models;
using WinApp.Services;
using System.Drawing.Imaging;
using PaddleOCRSharp;
using Microsoft.Web.WebView2.WinForms;
using Microsoft.Web.WebView2.Core;

namespace WinApp.Pages
{
    public partial class PageOcrActions : UIPage
    {
        private ActionOcr _selectedAction = null;
        private WebView2 _webView2;
        private PageImageMatchActions _pageImageMatchActions = null;
        public PageImageMatchActions ImageMatchPage
        {
            set { _pageImageMatchActions = value; }
        }
        

        public int X1
        {
            get => int.TryParse(txtLeftX.Text, out int x) ? x : 0;
            set => txtLeftX.Text = value.ToString();
        }

        public int Y1
        {
            get => int.TryParse(txtTopY.Text, out int y) ? y : 0;
            set => txtTopY.Text = value.ToString();
        }

        public int X2
        {
            get => int.TryParse(txtRightX.Text, out int x) ? x : 0;
            set => txtRightX.Text = value.ToString();
        }

        public int Y2
        {
            get => int.TryParse(txtBottomY.Text, out int y) ? y : 0;
            set => txtBottomY.Text = value.ToString();
        }

        public PageOcrActions(WebView2 webView2 = null)
        {
            _webView2 = webView2;
            InitializeComponent();
            dgvActions.AutoGenerateColumns = false;
            LoadData();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearInputs();
        }

        private void ValidateSaveButton()
        {
            if (string.IsNullOrWhiteSpace(txtName.Text))
            {
                btnSave.Enabled = false;
                return;
            }

            var actions = DataHelper.GetActionOcrs();
            if (_selectedAction == null) // 新增模式
            {
                btnSave.Enabled = !actions.Any(a => a.Name == txtName.Text);
            }
            else // 编辑模式
            {
                btnSave.Enabled = !actions.Any(a => a.Id != _selectedAction.Id && a.Name == txtName.Text);
            }
        }

        private void LoadData()
        {
            var actions = DataHelper.GetActionOcrs();
            dgvActions.DataSource = null;
            dgvActions.DataSource = actions;
        }
        private void ClearInputs()
        {
            txtName.Text = "";
            txtLeftX.Text = "0";
            txtTopY.Text = "0";
            txtRightX.Text = "0";
            txtBottomY.Text = "0";
            txtOcrResult.Text = "";
            _selectedAction = null;
            dgvActions.ClearSelection();
            titlePanel1.Text = "新增文字识别动作";
            ValidateSaveButton();
        }

        private void dgvActions_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvActions.SelectedRows.Count > 0)
            {
                _selectedAction = dgvActions.SelectedRows[0].DataBoundItem as ActionOcr;
                if (_selectedAction != null)
                {
                    txtName.Text = _selectedAction.Name;
                    txtLeftX.Text = _selectedAction.X.ToString();
                    txtTopY.Text = _selectedAction.Y.ToString();
                    txtRightX.Text = (_selectedAction.X + _selectedAction.Width).ToString();
                    txtBottomY.Text = (_selectedAction.Y + _selectedAction.Height).ToString();
                    titlePanel1.Text = "修改文字识别动作";
                    if(_selectedAction.ActionImageMatches.Count > 0) btnDelete.Visible = false;
                    else btnDelete.Visible = true;
                }
            }
            ValidateSaveButton();
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            ValidateSaveButton();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!int.TryParse(txtLeftX.Text, out int x1))
            {
                this.ShowWarningTip("X1坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtTopY.Text, out int y1))
            {
                this.ShowWarningTip("Y1坐标必须是整数");
                return;
            }
            if (!int.TryParse(txtRightX.Text, out int x2))
            {
                this.ShowWarningTip("X2坐标必须是整数");
                return;
            }

            if (!int.TryParse(txtBottomY.Text, out int y2))
            {
                this.ShowWarningTip("Y2坐标必须是整数");
                return;
            }

            try
            {
                if (_selectedAction == null) // 新增
                {
                    var action = new ActionOcr
                    {
                        Name = txtName.Text,
                        X = x1,
                        Y = y1,
                        Width = x2 - x1,
                        Height = y2 - y1
                    };
                    if (DataHelper.InsertActionOcr(action))
                    {
                        this.ShowSuccessTip("保存成功");
                        ClearInputs();
                        LoadData();
                    }
                }
                else // 修改
                {
                    bool hasImageMatches = _selectedAction.ActionImageMatches.Count > 0;
                    _selectedAction.Name = txtName.Text;
                    _selectedAction.X = x1;
                    _selectedAction.Y = y1;
                    _selectedAction.Width = x2 - x1;
                    _selectedAction.Height = y2 - y1;
                    if (DataHelper.UpdateActionOcr(_selectedAction))
                    {
                        this.ShowSuccessTip("保存成功");
                        ClearInputs();
                        LoadData();
                        // 如果有关联的图像匹配操作，刷新图像匹配页面
                        if (hasImageMatches && _pageImageMatchActions != null)
                        {
                            _pageImageMatchActions.Refresh();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                this.ShowErrorTip(ex.Message);
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (_selectedAction == null)
            {
                this.ShowWarningTip("请先选择要删除的文字识别动作");
                return;
            }

            if (this.ShowAskDialog($"确定要删除文字识别动作 [{_selectedAction.Name}] 吗？"))
            {
                try
                {
                    if (DataHelper.DeleteActionOcr(_selectedAction.Id))
                    {
                        this.ShowSuccessTip("删除成功");
                        ClearInputs();
                        LoadData();
                    }
                }
                catch (Exception ex)
                {
                    this.ShowErrorTip(ex.Message);
                }
            }
        }

        private async void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取截图区域坐标
                if (!int.TryParse(txtLeftX.Text, out int x1) || 
                    !int.TryParse(txtTopY.Text, out int y1) ||
                    !int.TryParse(txtRightX.Text, out int x2) ||
                    !int.TryParse(txtBottomY.Text, out int y2))
                {
                    this.ShowWarningTip("坐标值必须是有效的整数");
                    return;
                }

                // 获取截图区域
                var x = Math.Min(X1, X2);
                var y = Math.Min(Y1, Y2);
                var width = Math.Abs(X2 - X1);
                var height = Math.Abs(Y2 - Y1);

                if (width <= 0 || height <= 0)
                {
                    this.ShowWarningTip("请设置有效的截图区域");
                    return;
                }

                if (_webView2 == null)
                {
                    this.ShowWarningTip("WebView2控件未初始化");
                    return;
                }

                ActionOcr action = _selectedAction;
                if(action == null)
                {
                    action = new ActionOcr
                    {
                        X = x,
                        Y = y,
                        Width = width,
                        Height = height
                    };
                }
                action.WebView = _webView2;
                
                action.Completed += async (s, e) =>
                {
                    Point pos = Cursor.Position;
                    Point p = _webView2.PointToScreen(Point.Empty);
                    Point np = new Point(p.X + x, p.Y + y);
                    Cursor.Position = np;
                    this.ShowSuccessTip(e.Descprition);
                    Cursor.Position = pos;
                    txtOcrResult.Text = e.OcrResult;
                };
                await action.ExecuteAsync();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "OCR识别过程中发生错误");
                this.ShowErrorTip($"OCR识别失败：{ex.Message}");
            }
        }
    }
}
